package com.common.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SecurityFilter implements Filter {
	public static final String CONFIG_REDIRECTURL = "redirectURL";

	public static final String CONFIG_UN_RESTRICTED_RESOURCES = "unRestrictedResources";

	// 重定向URL
	private String redirectURL = "";

	// 检查跳过对象
	private Set<String> unRestrictedResources = new HashSet<String>();
	private String objName;
	
	public String getObjName() {
		return objName;
	}

	public void setObjName(String objName) {
		this.objName = objName;
	}
	public void destroy() {
	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		String currentUrl = request.getRequestURI();
//		String targetUrl = currentUrl.substring(currentUrl.indexOf("/", 1),
//				currentUrl.length());
		String targetUrl = currentUrl;

		boolean checkFlg = false;

		for (String unRestrictedResource : unRestrictedResources) {
			if (targetUrl.matches(unRestrictedResource)) {
				checkFlg = true;
				break;
			}
		}

		if (!checkFlg) {
			HttpSession session = request.getSession();
			Object obj = request.getSession().getAttribute(objName);
			if (session != null) {
				if (obj != null) {
					checkFlg = true;
				}
			}
		}
		
		if (checkFlg) {
			filterChain.doFilter(request, response);
		} else {
			response.sendRedirect(request.getContextPath() + this.redirectURL);
		}
	}

	public void init(FilterConfig config) throws ServletException {

		// 重定向URL
		this.redirectURL = config.getInitParameter(CONFIG_REDIRECTURL);
		// 检查跳过对象
		String unRestrictedRes = config.getInitParameter(CONFIG_UN_RESTRICTED_RESOURCES);
		unRestrictedResources.addAll(Arrays.asList(unRestrictedRes.split(",")));
		
		objName = config.getInitParameter("objName");
	}
}
